//
//  WebView.swift
//  ptbuy
//  加载html页面
//  Created by MyMac on 2025/1/7.
//

import SwiftUI
import WebKit

struct WebView: UIViewRepresentable {
    let htmlContent: String
   
    

        func makeUIView(context: Context) -> WKWebView {
            
           //配置WebView
            let contentController = WKUserContentController()
            contentController.add(context.coordinator, name: "chartClicked")
            
            let config = WKWebViewConfiguration()
            config.userContentController = contentController
            
            let webView = WKWebView(frame:.zero,configuration:config)

            
            //加载HTML内容
            if let htmlData = htmlContent.data(using: .utf8) {
                webView.load(htmlData, mimeType: "text/html", characterEncodingName: "utf-8", baseURL: URL(string: "about:blank")!)
            }
            return webView
        }

        func updateUIView(_ uiView: WKWebView, context: Context) {

        }

        func makeCoordinator() -> Coordinator {
            return Coordinator(parent: self)
        }

    
    class Coordinator: NSObject,WKScriptMessageHandler{
        var parent: WebView
                    
        init(parent: WebView) {
            self.parent = parent
        }
        func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
            if message.name == "chartClicked", let clickData = message.body as? [String:Any] {
                print("click data:\(clickData)")
            }
        }
    }
}
